#  -*- coding:utf-8 -*-
"""
@ author: 罗金盛
@ time: 2024/6/11
@ file: utils.py

"""
import logging
import os
from src.config import LoggerConfig
from src.spider.sinong_login import SinongLogin
import fitz  # PyMuPDF
from PIL import Image
import ddddocr
import time
import requests
from src.spider.auto_login import AuditLogin

LoggerConfig.configure_logger('log/sn-audit-report.log')


# LoggerConfig.configure_logger('../log/sn-audit-report.log')

def download_file(c02Code, fileName, save_path):
    """
    下载文件并保存到指定路径
    :param content (bytes): 文件内容
    :param save_path (str): 文件保存的路径
    :param file_name (str): 文件名
    """
    # 初始Cookies设置
    cookies = {
        'LastLoginTime': '2024/6/6_14:15:23',
        '.ASPXAUTH': 'F08DBA88E7F818175B89DAB7AE937B161DF823F5AE4122B5951C3B5F51A5EF6F17D3AC369B413D8D0349909DF470E6DDD8FE1049D8A0AAA2A5E264C41621069F1B214A962BA17E9D536AFE289BE4E1ED142449CCF93E5B6547F08D7D82F8C915335D3A46721843FFA8D0395DB86D6A478312379538B55B9695524B06F0B84C07A24B17B4E700D4357C48261E4394050144BDC9277865C802A1DD14FE87D7D05F7F6B35EA5E7D658A6B725057F94FA81630A2FEE2E3B4F4D11E838B10FBEC06EB9ED34E3B5E950A250E183D8FF7C7FAF017186527BF07803A108BC198B532EC1EC4F85A8B5A0AE12D7B234295FFD2D9022F718AEA9DC173BD5BDF0947589690D33715151DA6F48716D4D1934F56D26A7A95823DAB1F5DB1F01AB98612F3A247468ABD3DFDF27E8032E77117F395DBC294',
        'ASP.NET_SessionId': 'dnaixqr3i3xenta0ecjik0hq',
    }

    # 设置请求头
    headers = {
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Connection': 'keep-alive',
        'Content-Type': 'application/json;charset=UTF-8',
        'Origin': 'https://i-dev.sinongcpa.cn',
        'Referer': 'https://i-dev.sinongcpa.cn/f-cpscm/',
        'Sec-Fetch-Dest': 'empty',
        'Sec-Fetch-Mode': 'cors',
        'Sec-Fetch-Site': 'same-origin',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0',
        'sec-ch-ua': '"Microsoft Edge";v="125", "Chromium";v="125", "Not.A/Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
    }

    # 设置请求体
    json_data = {
        'c02Code': c02Code,
        'fileName': fileName,
    }

    response = requests.post('https://i-dev.sinongcpa.cn/cpscm/C02/GetFile', cookies=cookies, headers=headers,
                             json=json_data)

    # 检查响应状态码
    if response.status_code == 200:
        save_file(response.content, save_path, fileName)
    else:
        # 如果初次下载失败，尝试重新登录并再次下载
        sinong = SinongLogin()
        new_cookies = sinong.run()
        response = requests.post('https://i-dev.sinongcpa.cn/cpscm/C02/GetFile', cookies=new_cookies, headers=headers,
                                 json=json_data)
        if response.status_code == 200:
            save_file(response.content, save_path, fileName)
        else:
            logging.error(f"下载文件失败，状态码: {response.status_code}")


def save_file(content, save_path, file_name):
    """
    将文件内容保存到指定路径
    :param content (bytes): 文件内容
    :param save_path (str): 文件保存的路径
    :param file_name (str): 文件名
    """
    # 创建保存文件的完整路径
    full_path = os.path.join(save_path, file_name)

    # 确保保存路径存在
    os.makedirs(save_path, exist_ok=True)

    # 保存文件内容到指定路径
    with open(full_path, 'wb') as file:
        file.write(content)

    logging.info(f"文件已保存到: {full_path}")


# def identification_report_coding(pdf_path, zoom=10.0):
#     """
#     识别已赋码的审计报告PDF中的报告编码
#     :param pdf_path: pdf的文件路径 这里采用绝对路径去识别
#     :param zoom: 缩放倍率 越大裁剪的图像越清晰
#     :return:
#     """
#     try:
#         # 打开PDF文件
#         pdf_document = fitz.open(pdf_path)
#
#         # 获取第一页
#         page = pdf_document.load_page(0)
#
#         # 使用较高的分辨率转换为图像
#         matrix = fitz.Matrix(zoom, zoom)  # 设置缩放倍率
#         pix = page.get_pixmap(matrix=matrix)
#         img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
#
#         # 裁剪图像: 上面822像素，下面11像素，左边470像素，右边75像素  为了裁剪出合适的尺寸 这些地方的像素大小根据自己裁剪来的
#         left = int(470 * zoom)  # 左边裁剪470像素
#         top = int(822 * zoom)  # 上面裁剪822像素
#         right = img.width - int(75 * zoom)  # 右边裁剪75像素
#         bottom = img.height - int(11 * zoom)  # 下面裁剪11像素
#
#         cropped_image = img.crop((left, top, right, bottom))
#
#         # 裁剪后的图像尺寸
#         logging.info(f"文件裁剪完成，尺寸为: {cropped_image.size}")
#
#         # 保存裁剪后的图像为无损格式
#         cropped_image_path = "cropped_image.png"
#         cropped_image.save(cropped_image_path, format="PNG")
#
#         # 使用ddddocr进行文字识别
#         ocr = ddddocr.DdddOcr()
#         with open(cropped_image_path, 'rb') as f:
#             img_bytes = f.read()
#         recognized_text = ocr.classification(img_bytes)
#
#         return recognized_text
#
#     except Exception as e:
#         logging.error(f"识别出现异常: {e}")
#         return ""
#
#
# pdf_path = r'D:\Python_files\司农实习文件\Code\sn-audit-report\src\spider\directory\P2300841006_ro2.pdf'
# recognized_text = identification_report_coding(pdf_path)
#
# # 查找特定的文字
# target_text = "粤"
# if target_text in recognized_text:
#     print(f"报告编码为：{recognized_text.upper()}")


class ReportFetcher:
    def __init__(self):
        self.cookies = {
            'c39dd3f75d40-c30b-f4a4-f389-db517a85': 'WyIxNTQxNjY2NjM2Il0',
            'routeSign': '',
            'user_name': '%E5%B9%BF%E4%B8%9C%E5%8F%B8%E5%86%9C%E4%BC%9A%E8%AE%A1%E5%B8%88%E4%BA%8B%E5%8A%A1%E6%89%80%EF%BC%88%E7%89%B9%E6%AE%8A%E6%99%AE%E9%80%9A%E5%90%88%E4%BC%99%EF%BC%89',
            'USER_ACCOUNT': '44010293',
            'app_status': 'null',
            'transfer_status': 'null',
            'd1630c17-326a-4723-a68b-61354b3cccd4': 'WyIyNTc4NjM4NTEwIl0',
            'JSESSIONID': 'EEC4E57B055EB302ED270C247CD4E823',
            'PICID': 'PIC_ID_460670a8-95d7-4883-bf71-a9bd3d3654a1',
            'token_id': 'dea7d53f-7e0c-47cb-bd40-db589bad9ca6',
            'logintime': str(int(time.time() * 1000)),
        }

        self.headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Origin': 'http://acc.mof.gov.cn',
            'Proxy-Connection': 'keep-alive',
            'Referer': f'http://acc.mof.gov.cn/qrc/add.html?t={str(int(time.time() * 1000))}',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
        }

        self.data = {
            'reportYear': '2024',
            'qrcStatus': '1,2',
            'pageNo': '1',
            'pageSize': '1000',
        }

        self.base_url = 'http://acc.mof.gov.cn'

    def get_backnumber(self, file_no, cookies=None):
        try:
            response = requests.post(f'{self.base_url}/qrc/api/cpabreport/page', cookies=self.cookies,
                                     headers=self.headers, data=self.data, verify=False)
            response.raise_for_status()  # 如果响应状态码不是200，会引发HTTPError
            data_list = response.json().get('data', [])
            filtered_data = [
                {'clientCode': item.get('clientCode'), 'clientName': item.get('clientName'),
                 'fileNo': item.get('fileNo'),
                 'backNumber': item.get('backNumber')} for item in data_list]

            for index, item in enumerate(filtered_data):
                if item.get('fileNo') == file_no:
                    return item.get('backNumber'), index+1
            return [], -1

        except:
            audit = AuditLogin()
            self.cookies = audit.get_login_status()
            response = requests.post(f'{self.base_url}/qrc/api/cpabreport/page', cookies=self.cookies,
                                     headers=self.headers, data=self.data, verify=False)
            response.raise_for_status()  # 如果响应状态码不是200，会引发HTTPError
            data_list = response.json().get('data', [])
            filtered_data = [
                {'clientCode': item.get('clientCode'), 'clientName': item.get('clientName'),
                 'fileNo': item.get('fileNo'),
                 'backNumber': item.get('backNumber')} for item in data_list]

            for index, item in enumerate(filtered_data):
                if item.get('fileNo') == file_no:
                    return item.get('backNumber'), index+1
            return [], -1

if __name__ == '__main__':
    your_class_instance =ReportFetcher()
    back_number, index = your_class_instance.get_backnumber(file_no='司农审字[2024]24001280128号')

    print(f"BackNumber: {back_number}, Index: {index}")